//
//  SELocationManager.swift
//  SmartEyeForPatient
//
//  Created by qdsg on 2021/4/26.
//

import UIKit
import CoreLocation

class SELocationManager: NSObject {

    static let shared = SELocationManager()

    public var handler: ((SELocationModel?) -> Void)?

    private var latitude: Double = 0
    private var longitude: Double = 0

    private var target : UIViewController?

    private var locationManager = CLLocationManager()

    func startlocating(_ target: UIViewController?, _ handler: ((SELocationModel?) -> Void)?) {
        self.target = target
        self.handler = handler
        requestLocationAuthorizationStatus()
    }

    private func requestLocationAuthorizationStatus() {
        let status = CLLocationManager.authorizationStatus()
        switch status {
        case .notDetermined,
             .authorizedWhenInUse,
             .authorizedAlways:
            initLocationManager()
        default:
            showAlert()
        }
    }

    private func initLocationManager() {        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.distanceFilter = 100
        locationManager.delegate = self
        locationManager.requestWhenInUseAuthorization()
        locationManager.startUpdatingLocation()
    }

    private func showAlert() {
        handler?(nil)
        SEAlert.show(in: target, title: "定位服务未开启,是否前往开启?", confirmTitle: "去打开") { (action) in
            guard let url = URL(string: UIApplication.openSettingsURLString),
                UIApplication.shared.canOpenURL(url) else { return }
            UIApplication.shared.open(url, options: [:], completionHandler: nil)
        }
    }
}

extension SELocationManager: CLLocationManagerDelegate {
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let location = locations.last ?? CLLocation()
        let coordinate = location.coordinate
        latitude = coordinate.latitude
        longitude = coordinate.longitude
        manager.stopUpdatingLocation()
        translateToChinese(latitude, longitude)
    }

    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        requestLocationAuthorizationStatus()
    }

    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        requestLocationAuthorizationStatus()
    }
}

extension SELocationManager {
    private func translateToChinese(_ latitude: Double, _ longitude: Double) {
        let location = CLLocation(latitude: latitude, longitude: longitude)
        let geocoder = CLGeocoder()
        geocoder.reverseGeocodeLocation(location) { (placeMarks, error) in
            guard let placeMarks = placeMarks, let place = placeMarks.last else {
                self.handler?(nil)
                return
            }
            let model = SELocationModel(
                latitude: String(latitude),
                longitude: String(longitude),
                country: place.country ?? "",
                province: place.administrativeArea ?? "",
                city: place.locality ?? "",
                region: place.subLocality ?? "",
                street: place.thoroughfare ?? "",
                subStreet: place.subThoroughfare ?? "",
                location: place.name ?? "")
            self.handler?(model)
        }
    }
}
